package cn.itcast.bos.web.action.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.StandardService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@ParentPackage("json-default")
@Namespace("/")
@Actions
@Controller
@Scope("prototype")
public class StandardAction extends ActionSupport implements
		ModelDriven<Standard> {
	// 模型驱动注入
	private Standard standard = new Standard();

	@Override
	public Standard getModel() {
		return standard;
	}

	@Autowired
	private StandardService standardServcie;

	@Action(value = "standard_save", results = { @Result(name = "success", location = "/pages/base/standard.html", type = "redirect") })
	// 添加 取件标准的方法
	public String save() {
		System.out.println("������ɱ�׼,,,,");
		standardServcie.save(standard);
		return SUCCESS;
	}

	// 属性驱动 获取页面数据 page rows
	private int page;
	private int rows;

	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	// 分页查询 取件标准的方法 type="json"表明返回数据的类型是json
	@Action(value = "standard_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		// 调用业务层 查询数据 注意,页码是从0开始的
		Pageable pageable = new PageRequest(page - 1, rows);
		Page<Standard> pageData = standardServcie.findPageData(pageable);
		// 返回客户端数据 需要total 和rows
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", pageData.getTotalElements());
		result.put("rows", pageData.getContent());

		// 将map转换成json数据返回,使用struts2-json-plugin插件
		ActionContext.getContext().getValueStack().push(result);

		return SUCCESS;
	}

	// 查询所有 取件标准   并将数据已json形式  ,通过struts插件返回到页面
	@Action(value = "standard_findAll", results = { @Result(name = "success", type = "json") })
	public String findAll() {
		// 调用业务层 查询所有 取件标准
		List<Standard> standards = standardServcie.findAll();
		// 将数据通过 struts2的插件 转成json 
		ActionContext.getContext().getValueStack().push(standards);
		return SUCCESS;
	}
}
